//
//  NSDate+category.m
//  IAPDemo
//
//  Created by Charles.Yao on 2016/10/31.
//  Copyright © 2016年 com.pico. All rights reserved.
//

#import "NSDate+category.h"

@implementation NSDate (category)

+ (NSString *)chindDateFormate:(NSDate *)update{
   
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *destDateString = [dateFormatter stringFromDate:update];
    return destDateString;
}
+ (NSString *)convertDateToTimestamp:(NSString *)dateString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    
    NSDate *date = [formatter dateFromString:dateString];
    if (!date) {
        return nil; // 处理无效日期
    }
    
    NSTimeInterval timestamp = [date timeIntervalSince1970];
    return [NSString stringWithFormat:@"%.0f", timestamp];
}
+ (NSString *)convertToLocalTimeWithString:(NSString *)dateString andWithFormatter:(NSString *)fmt{
    // 1. 创建日期格式化器
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]]; // 固定格式处理
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
    
    // 2. 假设原始字符串是 UTC 时间（根据实际情况调整）
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    
    // 3. 将字符串转换为 NSDate
    NSDate *utcDate = [formatter dateFromString:dateString];
    
    // 4. 转换为当前时区的时间
    [formatter setTimeZone:[NSTimeZone systemTimeZone]]; // 系统当前时区
    NSString *localTimeString = [formatter stringFromDate:utcDate];
    
    // 5. 如果需要返回 NSDate（注意：NSDate 本身无时区概念）
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *localDate = [formatter dateFromString:localTimeString];
    
    // 查看转换结果
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:fmt];
    [outputFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *resultString = [outputFormatter stringFromDate:localDate];
    
    return resultString;
}
+ (NSString *)convert2LocalTimeWithString:(NSString *)dateString andWithFormatter:(NSString *)fmt {

    if (!dateString || dateString.length == 0) {
        return @"";
    }
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    inputFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    NSDate *date = [inputFormatter dateFromString:dateString];
    if (!date) {
        return @"";
    }
    
    //获取手机系统的当前时区
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    // 2️⃣ 输出格式
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    outputFormatter.dateFormat = fmt ?: @"yyyy-MM-dd HH:mm:ss";
    outputFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
    outputFormatter.timeZone = timeZone; // 转成本地

    return [outputFormatter stringFromDate:date];
}
@end
